package com.example.coreshopapp.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.coreshopapp.R;
import com.example.coreshopapp.bean.AddMemberReq;
import com.example.coreshopapp.bean.GoodsCategoryData;
import com.example.coreshopapp.bean.GradeData;
import com.example.coreshopapp.bean.OrderListReq;
import com.example.coreshopapp.task.GradeTask;
;
import com.example.coreshopapp.ui.LoginActivity;
import com.example.coreshopapp.utils.LoadingUtils;
import com.example.coreshopapp.utils.TimeUtils;
import com.example.coreshopapp.weight.CustomDatePickerDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import java.util.ArrayList;
import java.util.List;

import bean.OrderItemBean;

public class AddMemberFragment extends BottomSheetDialogFragment {
    private Spinner spn_class;
    private RadioGroup groupGender;
    private TextView birthday;
    private EditText etName, etMobile;
    private Button btnSubmit;
    private List<String> list_class; // 用于显示名字
    private List<GradeData> gradeList = new ArrayList<>();
    private ArrayAdapter<String> adp_class;
    private AddMemberReq memberInfo = new AddMemberReq();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("HandlerLeak")
    private Handler categoryHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    gradeList.clear();
                    gradeList = JSON.parseArray(msg.obj.toString(), GradeData.class);
                    initMemberClass();
                    break;
                case 9901:
                    Toast.makeText(requireContext(), "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(requireContext(), msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    Intent intent = new Intent(requireContext(), LoginActivity.class);
                    startActivity(intent);
                    Toast.makeText(requireContext(), msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_member_add, container, false);
        initView(view);
        viewClick();
        return view;
    }

    private void initView(View view) {
        spn_class = view.findViewById(R.id.sp_grade);
        groupGender = view.findViewById(R.id.groupGender);
        birthday = view.findViewById(R.id.tv_birthday);
        etName = view.findViewById(R.id.tv_name);
        etMobile = view.findViewById(R.id.tv_phone);
        btnSubmit = view.findViewById(R.id.btn_add_member);
        // 设置统一 TextWatcher
//        etName.addTextChangedListener(watcher);
//        etMobile.addTextChangedListener(watcher);

        view.findViewById(R.id.close).setOnClickListener(view1 -> {
            dismiss();
        });
        GradeTask gradeTask = new GradeTask();
        gradeTask.setOutHandler(categoryHandler);
        gradeTask.execute();

    }

    private void initMemberClass() {
        int mIndex = 0;
        int mRowsID = 0;
        list_class = new ArrayList<String>();
        for (GradeData mClassRow : gradeList) {
            list_class.add(mClassRow.getTitle());

            adp_class = new ArrayAdapter<String>(requireContext(),
                    R.layout.item_spinner_blue,
                    list_class);//适配器
            adp_class.setDropDownViewResource(R.layout.item_spinner_blue);//设置样式
            spn_class.setAdapter(adp_class);//加载适配器
            spn_class.setSelection(mIndex); // 选中 0

            memberInfo.setGrade(gradeList.get(0).getId());
            memberInfo.setSex(1);
            memberInfo.setStatus(1);
            memberInfo.setPassWord("123456");
        }

    }

    private void viewClick() {
        // 选中
        spn_class.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                memberInfo.setGrade(gradeList.get(i).getId());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        groupGender.setOnCheckedChangeListener((radioGroup, i) -> {
            RadioButton selected = radioGroup.findViewById(i);
            Log.d("viewClick: ", selected.getText().toString());
            String value = selected.getText().toString();
            if (value == "男") {
                memberInfo.setSex(1);
            } else {
                memberInfo.setSex(2);
            }
        });
        birthday.setOnClickListener(view -> {
            int year = TimeUtils.getYear();
            int month = TimeUtils.getMonth() - 1;
            int date = TimeUtils.getDay();
            if (memberInfo.getBirthday() != null) {
                String[] parts = memberInfo.getBirthday().toString().split("-");
                year = Integer.parseInt(parts[0]);
                month = Integer.parseInt(parts[1]) - 1;
                date = Integer.parseInt(parts[2]);
            }
            CustomDatePickerDialog startDialog = new CustomDatePickerDialog(requireContext(), 0, (startDatePicker, startYear, startMonthOfYear, startDayOfMonth) -> {
                String time = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                birthday.setText(time);
                memberInfo.setBirthday(time);
            }, year, month, date, false);
            startDialog.show();
        });
        btnSubmit.setOnClickListener(view -> {
            if (
                    memberInfo.getNickName() == null
                            || memberInfo.getMobile() == null
                            || !memberInfo.getMobile().matches("^1[3-9]\\d{9}$")
                            || memberInfo.getBirthday() == null
            ) {
                Toast.makeText(requireContext(), "请检查输入的值是否有误", Toast.LENGTH_SHORT).show();
                return;
            }
            if(setOnSubmitClickListener != null) {
                setOnSubmitClickListener.onSubmitClick(memberInfo);
            }
        });
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.d("name: ", etName.getText().toString().trim());
                memberInfo.setNickName(etName.getText().toString().trim());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                memberInfo.setMobile(etMobile.getText().toString().trim());
                memberInfo.setUserName(etMobile.getText().toString().trim());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
    // 添加
    public interface SetOnSubmitClickListener {
        void onSubmitClick(AddMemberReq addMemberReq); // 需要参数
    }
    private AddMemberFragment.SetOnSubmitClickListener setOnSubmitClickListener;

    public void setOnSubmitClickListener(AddMemberFragment.SetOnSubmitClickListener newClick) {
        setOnSubmitClickListener = newClick;
    }
}